//
// Created by Zsir on 2025/7/29.
//

#ifndef TCPSERVER_TCPSERVER_H
#define TCPSERVER_TCPSERVER_H

#include <netinet/in.h>
#include <cstring>
#include "arpa/inet.h"
#include <cstdio>
#include <sys/epoll.h>
#include "Thread.h"
#include "sys/socket.h"

#define EPOLL_SIZE 1024

using RCALLBACK = std::function<int(int)>;

struct conn
{
    int fd;
    char rbuffer[1024];
    int rlength;

    char wbuffer[1024];
    int wlength;

    RCALLBACK send_callback;

    union
    {
        RCALLBACK recv_callback;
        RCALLBACK accept_callback;
    } r_action;
};

class TcpServer
{
public:
    using Func = void *(*)(void *);

    explicit TcpServer(int port, int maxPort);

    ~TcpServer();

    int bind();

    int listen();

    int accept();

    int accept_epoll();

    int accept_poll();

    int isListenFd(int fd);

    int accept_select();

    int accept_reactor();

    int set_event(int fd, int event,int flag);

    int accept_cb(int fd);

    int recv_cb(int fd);

    int send_cb(int fd);

private:
    static void *clientFunc(void *arg);

    int sockfd_{};
    int port_;
    struct sockaddr_in addr_{};
    int epfd_;
    struct epoll_event ev_{};
    int *sockfds_;

    int maxPort_;
};

#endif //TCPSERVER_TCPSERVER_H
